import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;

/**
 * Cria um socket multicast e envia o valor de um contador a cada segundo
 * 
 */
public class MultiCounter extends Thread {
	
	private String destinationGroup;
	
	InetAddress ia;
	int port = 0;	
	
	public MultiCounter (String destinationGroup, String destinationPort) throws Exception {
		this.destinationGroup = destinationGroup;
		
		try {
			ia = InetAddress.getByName(destinationGroup);
			port = Integer.parseInt(destinationPort);
		} catch (Exception e) {
			System.err.println("Erro nos parâmetros: " + e.getMessage());
			e.printStackTrace();
			throw e;
		}
	}

	public void run () {
		int i = 0;

		try {
			MulticastSocket ms = new MulticastSocket();
			ms.joinGroup(ia);
			
			while(true) {
				String message = "Contador = " + i++;
				byte[] data = message.getBytes();
				//message.getBytes(0, message.length(), data, 0);
				DatagramPacket dp = new DatagramPacket(data, data.length, ia, port);
				ms.setTimeToLive(5);
				System.out.println("Enviando [" + message + "] para grupo " + destinationGroup + " porta " + port);
				ms.send(dp);
				try {
					Thread.sleep(15 * 1000);   // 10 s
				} catch (InterruptedException e) {
				}
			}

		} catch (SocketException se) {
			System.err.println(se);
		} catch (IOException ie) {
			System.err.println(ie);
		}	
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {

		try {
			MultiCounter counter = new MultiCounter("224.5.5.1", "27000");
			counter.start();
			counter.join(); 
		} catch (InterruptedException e) {
			System.out.println("Finalizando execução...");
		} catch (Exception e) {
			System.err.println("Erro no envio de pacotes multicast. Mensage = " + e.getMessage());
			e.printStackTrace();
		}

	}

}
